package stark.app.function.applock;

import android.os.Build;
import android.view.View;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.applock.lib.AppLockBean;
import com.stark.applock.lib.AppLockModule;
import com.stark.applock.lib.AppLockUtil;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import stark.app.R;
import stark.app.databinding.ActivityAppLockDemoBinding;
import stark.common.basic.base.BaseNoModelActivity;

/**
 * Author：daizhongbin on 2022/8/2
 * Email：1027154338@qq.com
 * Desc:
 */
public class AppLockDemoActivity extends BaseNoModelActivity<ActivityAppLockDemoBinding> {

    private static final int REQ_USAGE_PER = 1;
    private AppAdapter mLockedAppAdapter;

    @Override
    protected int onCreate() {
        return R.layout.activity_app_lock_demo;
    }

    @Override
    protected void initView() {
        //注意：这里设置的应用解锁界面Activity的launchMode需为singleTask
        AppLockModule.init(AppUnlockActivity.class);
        //测试用:设置解锁密码，正式项目中需要有专门的设置密码界面供用户设置解锁密码
        AppLockModule.setUnlockPassword("6666");

        mDataBinding.llOpenAppLock.setOnClickListener(v -> {
            handleClickOpenLock();
        });
        mDataBinding.switchLock.setOnClickListener(v -> {
            handleClickOpenLock();
        });
        if (AppLockModule.isAppLockOpened()) {
            mDataBinding.switchLock.setChecked(true);
            AppLockModule.startAppLockService();
        } else {
            mDataBinding.switchLock.setChecked(false);
        }

        mDataBinding.btnEnterApp.setOnClickListener(v -> {
            startActivity(AppLockAppsActivity.class);
        });

        mDataBinding.btnDelayTime.setOnClickListener(v -> {
            handleClickDelayTime();
        });
        updateDelayOpenedView();
        updateDelayTimeView();
        mDataBinding.btnDelay5.setOnClickListener(v -> {
            AppLockModule.setDelayTime(5);
            updateDelayTimeView();
        });
        mDataBinding.btnDelay10.setOnClickListener(v -> {
            AppLockModule.setDelayTime(10);
            updateDelayTimeView();
        });

        //rv
        mDataBinding.rvLockedApp.setLayoutManager(new LinearLayoutManager(this));
        AppAdapter appAdapter = new AppAdapter();
        appAdapter.setOnItemClickListener(this);
        mLockedAppAdapter = appAdapter;
        mDataBinding.rvLockedApp.setAdapter(appAdapter);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        mLockedAppAdapter.setNewInstance(AppLockModule.getLockedApps());
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        AppLockBean bean = mLockedAppAdapter.getItem(position);
        AppLockModule.unlockApp(bean.pckName);
        mLockedAppAdapter.removeAt(position);
    }

    private void handleClickOpenLock() {
        //先判断是否有应用使用情况记录的权限
        if (!AppLockUtil.hasUsageStatsPermission()) {
            AppLockUtil.reqUsageStatsPermission(this, REQ_USAGE_PER);
            return;
        }

        //再判断是否有悬浮窗权限（该权限可使应用能在后台拉起activity，否则无法启动activity）
        if (!isGrantedDrawOverlays() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionUtils.requestDrawOverlays(new PermissionUtils.SimpleCallback() {
                @Override
                public void onGranted() {
                }

                @Override
                public void onDenied() {
                }
            });
            return;
        }

        if (!AppLockModule.hasLookGuide()) {
            //弹对话框，开发人员自己去实现，这里demo只做个提示
            ToastUtils.showShort("首次使用该应用，请前往查看相应权限");
            AppLockModule.setLookGuide(true);
            return;
        }

        if (AppLockModule.isAppLockOpened()) {
            AppLockModule.setAppLockOpened(false);
            mDataBinding.switchLock.setChecked(false);
        } else {
            AppLockModule.setAppLockOpened(true);
            mDataBinding.switchLock.setChecked(true);
        }

    }

    private void handleClickDelayTime() {
        AppLockModule.setDelayOpened(!AppLockModule.isDelayOpened());
        updateDelayOpenedView();
    }

    private void updateDelayOpenedView() {
        if (AppLockModule.isDelayOpened()) {
            mDataBinding.btnDelayTime.setText("延时开关已开");
        } else {
            mDataBinding.btnDelayTime.setText("延时开关已关");
        }
    }

    private void updateDelayTimeView() {
        int delayTime = (int) AppLockModule.getDelayTime();
        mDataBinding.tvCurDelayTime.setText("当前延时" + delayTime + "秒");
    }

    private boolean isGrantedDrawOverlays() {
        boolean has = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            has = PermissionUtils.isGrantedDrawOverlays();
        }
        return has;
    }
}
